package com.cuitrip.business.bill;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.business.bill.model.BillData;
import com.cuitrip.business.bill.model.Bills;
import com.cuitrip.component.page.SimpleEmptyFragmentActivity;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.component.list.CTRecyclerView;
import com.lab.component.list.event.OnMoreListener;
import com.lab.component.list.simple.CTSimpleRecyclerAdapter;
import com.lab.component.list.simple.CTSimpleViewHolder;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ImageHelper;
import com.lab.utils.NumberUtils;
import com.lab.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by sheena on 16/4/28.
 */
public class TransactionFragment extends CustomUiFragment implements IProxyCallback, OnMoreListener {

    public static final int DEFAULT_SIZE = 10;
    @Bind(R.id.ct_recycler_view)
    protected CTRecyclerView mCtRecyclerView;
    @Bind(R.id.ll_no_data_container)
    LinearLayout noDataContainer;
    private int index = 0;
    private boolean isRefresh = true;

    private ApiProxy mApiProxy = new ApiProxy(this);
    private ArrayList<BillData> billDataList = new ArrayList<>();
    private CTSimpleRecyclerAdapter mAdapter;

    public static TransactionFragment newInstance() {
        TransactionFragment transactionFragment = new TransactionFragment();
        Bundle bundle = new Bundle();
        transactionFragment.setArguments(bundle);
        return transactionFragment;
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mLeftStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.transaction);
        return config;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_transaction);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        setupMoreLeftCount(5);
    }

    private void setupMoreLeftCount(int defaultSize) {
        mCtRecyclerView.setupMoreListener(this, defaultSize);
    }


    @Override
    public void initData() {
        OrderBusiness.getBills(mApiProxy, index * DEFAULT_SIZE, DEFAULT_SIZE);
        showNoCancelDialog();
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(AppCoreRuntime.context, LinearLayoutManager.VERTICAL, false);
        mCtRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new CTSimpleRecyclerAdapter<BillData>(AppCoreRuntime.context, billDataList) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.bill_item;
            }

            @Override
            public void onNewViewHolder(CTSimpleViewHolder viewHolder, ViewGroup parent, int viewType) {
            }

            @Override
            public void bindData(CTSimpleViewHolder holder, final int position, final BillData item) {
                int type = item.getType();
                renderData(type, holder, item);
                holder.getView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle args = new Bundle();
                        String billId = item.getBillId();
                        args.putString("billId", billId);
                        switch (item.getType()) {
                            case BillData.POST:
                                TrackUtil.trackScreenName("/insider/transactions/detail");
                                SimpleEmptyFragmentActivity.startFragmentActivity(getHostActivity(), BillDetailFragment.class, args);
                                break;
                            case BillData.WITHDRAW://提现
                                TrackUtil.trackScreenName("/insider/transactions/withdraw");
                                SimpleEmptyFragmentActivity.startFragmentActivity(getHostActivity(), CashDetailFragment.class, args);
                                break;
                            case BillData.REWARD://奖励
                            case BillData.PENALTY://罚款
                                //金额、币种、时间
                                int type = item.getType();
                                String money = item.getMoney();
                                String moneyType = item.getMoneyType();
                                String time = Long.toString(item.getGmtCreated());
                                RewardFragment.startFragment(getHostActivity(), money, moneyType, time, type);
                                break;

                        }
                    }
                });


            }


        };

        mCtRecyclerView.setAdapter(mAdapter);
    }

    private void renderData(int type, CTSimpleViewHolder holder, BillData item) {
        CircleImageView avaImage = holder.getView(R.id.image);
        TextView billUser = holder.getView(R.id.billUser);
        TextView cashPrice = holder.getView(R.id.cashPrice);
        TextView status = holder.getView(R.id.status);
        status.setText(formatStatus(item.getStatus()));
        TextView time = holder.getView(R.id.time);
        time.setText(TimeUtil.formatTime(InputTime.build(item.getGmtCreated()), OutputTime.getLocalInstance(OutputTime.OutputType.Type_DAY)));
        boolean flag = item.getStatus() == 3;

        switch (type) {
            case BillData.POST:
                cashPrice.setTextColor(ResourceUtil.getColor(R.color.orange_ff6855));
                ImageHelper.displayPersonImage(item.getHeadPic(), avaImage, null);
                billUser.setText(item.getUserNick());
                cashPrice.setText(item.getCashCurrency() + " +" + NumberUtils.getMoneyFormat(item.getCashPrice()));
                break;
            case BillData.WITHDRAW:
                cashPrice.setTextColor(ResourceUtil.getColor(flag ? R.color.hint : R.color.apple_7ecc1e));
                billUser.setTextColor(ResourceUtil.getColor(flag ? R.color.hint : R.color.ct_black));
                avaImage.setImageResource(R.drawable.withdrawal_icon);
                billUser.setText(R.string.withdraw);
                SpannableString ss = new SpannableString(item.getCashCurrency() + " -" + NumberUtils.getMoneyFormat(item.getCashPrice()));
                ss.setSpan(new StrikethroughSpan(), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (flag) {
                    cashPrice.setText(ss);
                } else {
                    cashPrice.setText(item.getCashCurrency() + " -" + NumberUtils.getMoneyFormat(item.getCashPrice()));
                }
                break;
            case BillData.REWARD:
                cashPrice.setTextColor(ResourceUtil.getColor(R.color.orange_ff6855));
                avaImage.setImageResource(R.drawable.reward);
                billUser.setText(R.string.transaction_attribute_type_reward);
                cashPrice.setText(item.getCashCurrency() + " +" + NumberUtils.getMoneyFormat(item.getCashPrice()));
                break;
            case BillData.PENALTY:
                avaImage.setImageResource(R.drawable.penalty_fee);
                billUser.setText(R.string.wallet_transaction_type_penalty);
                cashPrice.setTextColor(ResourceUtil.getColor(flag ? R.color.hint : R.color.apple_7ecc1e));
                cashPrice.setText(item.getCashCurrency() + " -" + NumberUtils.getMoneyFormat(item.getCashPrice()));
                break;

        }
    }

    private String formatStatus(int status) {
        switch (status) {
            case 0:
                return getString(R.string.wallet_transaction_state_received);
            case 1:
                return getString(R.string.wallet_transaction_state_processing);
            case 2:
                return getString(R.string.book_state_finished);
            case 3:
                return getString(R.string.wallet_transaction_state_failed);
            default:
                return null;

        }
    }


    @Override
    public void initListener() {

        mCtRecyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                mCtRecyclerView.setHasMore(true);
                OrderBusiness.getBills(mApiProxy, index * DEFAULT_SIZE, DEFAULT_SIZE);
            }
        });

        mCtRecyclerView.setRefreshing(true);
    }


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()){
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        mCtRecyclerView.setRefreshing(false);
        if (response.isResponseNormal()) {
            if (response.result instanceof Bills) {
                Bills bills = (Bills) response.result;
                List<BillData> list = bills.getLists();
                if (list != null) {
                    if (list.size() == 0) {
                        mCtRecyclerView.setHasMore(false);
                    }else {
                        if (isRefresh) {
                            billDataList.clear();
                        }
                        billDataList.addAll(list);
                        mAdapter.notifyDataSetChanged();
                        isRefresh = false;
                    }
                    noDataContainer.setVisibility(View.GONE);
                } else {
                    noDataContainer.setVisibility(View.VISIBLE);
                }
                hideNoCancelDialog();
                return false;
            }
        } else {
            hideNoCancelDialog();
            ToastUtil.toast(getContext(), response.msg, 0);
            return false;
        }
        return false;
    }

    @Override
    public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
        mCtRecyclerView.showMoreProgress();
        OrderBusiness.getBills(mApiProxy, overallItemsCount, DEFAULT_SIZE);

    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }
}
